//
// Created by gd on 2019/12/1.
//

#include "server.h"
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string>
#include <unistd.h>
#include <thread>

void voiceServer() {
  int sock_fd = socket(AF_INET, SOCK_DGRAM, 0);
  struct sockaddr_in addr_serv;
  int len;
  memset(&addr_serv, 0, sizeof(struct sockaddr_in));
  addr_serv.sin_family = AF_INET;
  addr_serv.sin_port = htons(1010);
  addr_serv.sin_addr.s_addr = htonl(INADDR_ANY);
  len = sizeof(addr_serv);
  bind(sock_fd, (struct sockaddr *)&addr_serv, sizeof(addr_serv));

  int recv_num;
  char recv_buf[64000];
  struct sockaddr_in addr_client;

  while (1) {
    recv_num = recvfrom(sock_fd, recv_buf, sizeof(recv_buf), 0, (struct sockaddr *)&addr_client, (socklen_t *)&len);
    printf("voice received: %d\n", recv_num);
  }
}

void textServer() {
  int sock_fd = socket(AF_INET, SOCK_DGRAM, 0);
  struct sockaddr_in addr_serv;
  int len;
  memset(&addr_serv, 0, sizeof(struct sockaddr_in));
  addr_serv.sin_family = AF_INET;
  addr_serv.sin_port = htons(2020);
  addr_serv.sin_addr.s_addr = htonl(INADDR_ANY);
  len = sizeof(addr_serv);
  bind(sock_fd, (struct sockaddr *)&addr_serv, sizeof(addr_serv));

  int recv_num;
  char recv_buf[64000];
  struct sockaddr_in addr_client;

  while (1) {
    recv_num = recvfrom(sock_fd, recv_buf, sizeof(recv_buf), 0, (struct sockaddr *)&addr_client, (socklen_t *)&len);
    printf("text received: %d\n", recv_num);
  }
}

Server::Server() {
  std::thread vs(voiceServer);
  std::thread ts(textServer);
  vs.detach();
  ts.detach();
}
